package com.CuandoLlegaAndroid.Helpers;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.protocol.HTTP;

import com.CuandoLlegaAndroid.DDLModels.BusLine;
import com.CuandoLlegaAndroid.DDLModels.Street;

public final class HTMLHelper {

	public static String convertStreamToString(InputStream is) {

		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		StringBuilder sb = new StringBuilder();
		String line = null;

		try {
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}

		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return sb.toString();
	}

	public static String GetPost(String fullUri) {

		HttpClient client = new DefaultHttpClient(GetHttpParameters());
		HttpGet request = new HttpGet();

		try {
			request.setURI(new URI(fullUri));
			HttpResponse response = client.execute(request);

			if (response != null) {

				HttpEntity entity = response.getEntity();
				if (entity != null) {

					InputStream instream = entity.getContent();
					String result= HTMLHelper.convertStreamToString(instream);	

					return result;
				}
			}
			return "";
		} catch (URISyntaxException e) {
			e.printStackTrace();
			return "";
		} catch (ClientProtocolException e) {
			e.printStackTrace();
			return "";
		} catch (IOException e) {
			e.printStackTrace();
			return "";
		}
	}

	public static String GetWhenArrive(final String idLine, final String nro, final BusLine bs, final Street si, final Street ss)
	{

		try {
			HttpClient client = new DefaultHttpClient(GetHttpParameters());  
			String postURL = "http://www.etr.gov.ar/getSmsResponse.php";
			HttpPost post = new HttpPost(postURL); 


			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("parada", nro));
			params.add(new BasicNameValuePair("linea", idLine));
			UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params,HTTP.UTF_8);
			post.setEntity(ent);
			HttpResponse responsePOST = client.execute(post);  

			HttpEntity resEntity = responsePOST.getEntity(); 

			InputStream instream = resEntity.getContent();
			//History log
//			try {
//
//				Thread checkUpdate = new Thread() {  
//					public void run() {
//						try {
//
//							String idCalle = ""; 
//							String nombreCalle = ""; 
//							String idIntersect = ""; 
//							String nombreIntersec = ""; 
//							String nombreLinea = "";
//
//							if(ss!=null){
//								idCalle = ss.ID;
//								nombreCalle = ss.Name;
//							}
//							if(si!=null){
//								idIntersect = si.ID;
//								nombreIntersec = si.Name;
//							}
//							if(bs!=null){
//								nombreLinea = bs.Name;
//							}
//
//
//							URL url = new URL(fullUri);
//							URI uri = new URI(url.getProtocol(), url.getHost(), url.getPath(), url.getQuery(), null);
//
//
//							HttpClient clientGet = new DefaultHttpClient(GetHttpParameters());
//
//							HttpGet request = new HttpGet();
//							request.setURI(uri);
//
//							clientGet.execute(request);
//						} catch (ClientProtocolException e) {
//							e.printStackTrace();
//						} catch (IOException e) {
//							e.printStackTrace();
//						} catch (URISyntaxException e) {
//							e.printStackTrace();
//						}catch(Exception e){
//							e.printStackTrace();
//						}
//					}
//				};
//				checkUpdate.start();
//
//
//
//			} catch (Exception e) {
//				e.printStackTrace();
//			}

			return HTMLHelper.convertStreamToString(instream);

		} catch (Exception e) {
			e.printStackTrace();
			return "error";
		}
	}

	public static ArrayList<String> FormatNroParada(String txtHtml)
	{

		String cleantxt = txtHtml.replaceAll("[\n]", "");

		Pattern txtPatter = Pattern.compile("(?<=^|>)[^<]+?(?=<|$)");
		Matcher txtMatch = txtPatter.matcher(cleantxt);


		ArrayList<String> sa = new ArrayList<String>();

		while(txtMatch.find())
		{	
			String nroH = txtMatch.group();

			if(nroH!=null && nroH.trim()!=null && nroH.trim().length()!=0)
			{
				if(!nroH.contains("$")){
					sa.add(nroH);
				}
			}
		}

		return sa;
	}

	private static BasicHttpParams GetHttpParameters()
	{
		BasicHttpParams httpParameters = new BasicHttpParams();
		// Set the timeout in milliseconds until a connection is established.
		int timeoutConnection = 5000;
		HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
		// Set the default socket timeout (SO_TIMEOUT) 
		// in milliseconds which is the timeout for waiting for data.
		int timeoutSocket = 5000;
		HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

		return httpParameters;
	}


}
